package com.niiwoo.civet.trade.service.local.statisticsinfo;


import com.niiwoo.activity.stage.enums.prize.DeadLineUnitEnum;
import com.niiwoo.civet.base.enums.DeadlineUnitEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestOrderMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dto.request.thirdplateformdata.WangDaiTianYanRequestDTO;
import com.niiwoo.civet.trade.dto.response.thirdplateformdata.WangDaiTianYanResponseDTO;
import com.niiwoo.civet.trade.enums.*;
import com.niiwoo.tripod.base.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by bincun on 2018/8/31.
 * 网贷天眼
 */
@Service
@Slf4j
public class WangdaitianyanLocalService {
    @Autowired
    private ProjectMapperExt projectMapperExt;
    @Autowired
    private ProjectInvestOrderMapperExt projectInvestOrderMapperExt;
    @Value("${h5-niiwoo-project-detail-url}")
    private String h5BorrowDetailUrl;

    private static String plateform_name = "你我金融";

    public WangDaiTianYanResponseDTO getProjectsByDate(WangDaiTianYanRequestDTO dto){
        WangDaiTianYanResponseDTO responseDTO = new WangDaiTianYanResponseDTO();
        int start = 0;
        if (dto.getPageIndex() > 1){
            start  = dto.getPageSize() * (dto.getPageIndex()-1);
        }
        int countNum = 0; //标的总数
        List<Project> list;
        if (dto.getStatus() == 1) {//已满标
            Long countNumLong = (Long) projectMapperExt.countFullProjectByDate(dto.getTimeFrom(),dto.getTimeTo()).get("countNum");
            countNum = countNumLong.intValue();
            list = projectMapperExt.selectFullProjectByDate(dto.getTimeFrom(),dto.getTimeTo(),start,dto.getPageSize());
        }else{
            countNum = projectMapperExt.countInvestingProjectByDate(dto.getTimeFrom(),dto.getTimeTo());
            list = projectMapperExt.selectInvestingProjectByDate(dto.getTimeFrom(),dto.getTimeTo(),start,dto.getPageSize());
        }
        List<Map<String,String>> loans = new ArrayList<>();
        for (Project project : list) {
            Integer investNum = projectInvestOrderMapperExt.countInvested(project.getProjectId());
            Map<String,String> loan = new HashMap<>();
            loan.put("id",project.getProjectId().toString());
            loan.put("platform_name", plateform_name);
            loan.put("url",h5BorrowDetailUrl+project.getProjectId());
            loan.put("title",project.getTitle());
            loan.put("username",project.getBorrowUserId());
            loan.put("userid",project.getBorrowUserId());
            loan.put("status",(project.getStatus()==2 ? "0":"1"));
            loan.put("c_type",this.getCtyppFromProject(project).toString());
            loan.put("amount",project.getContractAmount().toString());
            loan.put("rate",project.getBorrowRate().toString());
            loan.put("period",project.getDeadline().toString());
            loan.put("p_type",DeadlineUnitEnum.BY_MONTH.getDeadlineUnit().equals(project.getDeadlineUnit())? "1":"0");//0 代表天,1 代表月.
            loan.put("pay_way",this.getPayWayStr(project));
            String process = "1.0";//默认进度 100%
            if (ProjectStatusEnum.COLLECTING.getStatus().equals(project.getStatus())){
                process = project.getInvestedAmount().divide(project.getContractAmount(),1, BigDecimal.ROUND_DOWN).toString();
            }            loan.put("start_time", DateUtils.format(project.getCreateTime(),DateUtils.SHOW_DATETIME_FORMAT));
            loan.put("process",process);
            loan.put("end_time",DateUtils.format(project.getFullSuccessTime(),DateUtils.SHOW_DATETIME_FORMAT));
            loan.put("invest_num",investNum.toString());
            loans.add(loan);
        }
        responseDTO.setPage_count(countNum % dto.getPageSize() == 0 ?countNum/dto.getPageSize() : countNum/dto.getPageSize()+1);
        responseDTO.setPage_index(dto.getPageIndex());
        responseDTO.setResult_code(1);
        responseDTO.setResult_msg("成功");
        responseDTO.setLoans(loans);
        return responseDTO;
    }

    /**
     * 0 代表其他;
     * 1 按月等额本息还款;
     * 2 按月付息,到期还本;
     * 3 按天计息,一次性还本付息;
     * 4,按月计息,一次性还本付息;
     * 5 按季分期还款;
     * 6 为等额本金,按月还本金;
     * 7 先息期本;
     * 8 按季付息,到期还本;
     * 9 按半年付息,到期还本;
     * 10 按年付息，到期还本.
     * @param project
     * @return
     */
    private String getPayWayStr(Project project){
        String result = "1";
        if (RepaymentTypeEnum.MONTHLY_INTEREST_PAYMENT_DUE.getValue().equals(project.getRepaymentType())){
            result = "2";
        }else if (RepaymentTypeEnum.AVERAGE_CAPITAL_PLUS_INTEREST.getValue().equals(project.getRepaymentType())){
            result = "1";
        }else if (RepaymentTypeEnum.REPAY_PRINCIPAL_INTEREST_AT_TERM.getValue().equals(project.getRepaymentType())){
            result = "4";
        }
        return result;
    }

    /**
     * 返回类型处，c_type类型：
     0.1：信用标-个人信贷
     0.2：信用标-企业信贷
     0.3：信用标-消费金融
     0.4：信用标-农村金融
     0.5：信用标-供应链金融
     1 担保标
     2.1：抵押、质押标-车贷
     2.2：抵押、质押标-房贷
     2.3：抵押、质押标-票据
     2.4：抵押、质押标-融资租赁
     3 秒标;
     4 债权转让标(流转标,二级市场标的);5 理财计划(宝类业务_活期);
     6 其它;7 净值标;8 活动标(体验标).9 理财计划(宝类业务_定期).
     3，4，5标类型不参与贷款余额计算；请注意
     5【理财计划(宝类业务_活期)】和9【理财计划(宝类业务_定期)】的区分；
     4债权转让标指的是不会产生新待还的转让，如果会产生新待还，请返回其他标类型.
     * @param project
     * @return
     */
    private Float getCtyppFromProject(Project project) {
        Float result = 0.1F;//个人信用贷.
        //信贷
        if ((LoanTypeEnum.CREDIT_CARD_LOAN.getValue().equals(project.getLoanType()))
                || LoanTypeEnum.SPEED_LOAN.getValue().equals(project.getLoanType())
                || LoanTypeEnum.SOCIAL_SECURITY_LOAN.getValue().equals(project.getLoanType())){
            if (BorrowerTypeEnum.COMPANY.getType().equals(project.getBorrowerType()) ) {//企业
                result = 0.2F;
            } else {
                result = 0.1F;
            }
        }else if (LoanTypeEnum.SUPPLY_CHAIN_LOAN.getValue().equals(project.getLoanType())){
            result = 0.5F;
        }else if (LoanTypeEnum.VEHICLE_MORTGAGE_LOAN.getValue().equals(project.getLoanType())){
            result = 2.2F;
        }else if (LoanTypeEnum.HOUSE_MORTGAGE_LOAN.getValue().equals(project.getLoanType())){
            result  = 2.1F;
        }else {
            log.info("借款类型无法对应，使用默认类型：个人信用贷.");
        }
        return result;
    }

    /**
     * 查投资订单
     * @param dto
     * @return
     */
    public WangDaiTianYanResponseDTO getInvestorOrders(WangDaiTianYanRequestDTO dto){
        WangDaiTianYanResponseDTO responseDTO = new WangDaiTianYanResponseDTO();
        int start = 0;
        if (dto.getPageIndex() > 1){
            start  = dto.getPageSize() * (dto.getPageIndex()-1);
        }
        int countNum = 0; //标的总数
        List<ProjectInvestOrder> list;
        if (dto.getStatus() == 1) {//已满标
            countNum = projectInvestOrderMapperExt.countFullInvestedListByTime(dto.getTimeFrom(),dto.getTimeTo());
            list = projectInvestOrderMapperExt.selectFullInvestedListByTime(dto.getTimeFrom(),dto.getTimeTo(),start,dto.getPageSize());
        }else{
            countNum = projectInvestOrderMapperExt.countInvestingListByTime(dto.getTimeFrom(),dto.getTimeTo());
            list = projectInvestOrderMapperExt.selectInvestingListByTime(dto.getTimeFrom(),dto.getTimeTo(),start,dto.getPageSize());
        }
        List<Map<String,String>> loans = new ArrayList<>();
        for (ProjectInvestOrder investOrder : list) {
            Map<String,String> loan = new HashMap<>();
            loan.put("id",investOrder.getProjectId().toString());
            loan.put("link",h5BorrowDetailUrl+investOrder.getProjectId());
            loan.put("username",investOrder.getUserId());
            loan.put("userid",investOrder.getUserId());
            loan.put("type", InvestWayEnum.AUTO.getValue().equals(investOrder.getInvestType())? "自动":"手动");
            loan.put("money", Byte.valueOf("2").equals(investOrder.getInvestType())?investOrder.getShare()+"":investOrder.getAmount()+"");//债转标时，取份额，否则取投资金额
            loan.put("account",loan.get("money"));
            loan.put("status","成功");//检索出来的都是成功的
            loan.put("add_time",DateUtils.format(investOrder.getCreateTime(),DateUtils.SHOW_DATETIME_FORMAT));
            loans.add(loan);
        }
        responseDTO.setPage_count(countNum % dto.getPageSize() == 0 ?countNum/dto.getPageSize() : countNum/dto.getPageSize()+1);
        responseDTO.setPage_index(dto.getPageIndex());
        responseDTO.setResult_code(1);
        responseDTO.setResult_msg("成功");
        responseDTO.setLoans(loans);
        return responseDTO;
    }

    public WangDaiTianYanResponseDTO getOverdebtProjects(WangDaiTianYanRequestDTO dto){
        WangDaiTianYanResponseDTO responseDTO = new WangDaiTianYanResponseDTO();
        int start = 0;
        if (dto.getPageIndex() > 1){
            start  = dto.getPageSize() * (dto.getPageIndex()-1);
        }
        int countNum = 0; //标的总数
        List<ProjectForTianyan> list;
        List<Map<String,String>> loans = new ArrayList<>();
        if (dto.getStatus() == 1) {//已满标
            countNum = projectMapperExt.countOverdebtProjects(dto.getTimeFrom(),dto.getTimeTo());
            list = projectMapperExt.selectOverdebtProjects(dto.getTimeFrom(),dto.getTimeTo(),start,dto.getPageSize());
            for (ProjectForTianyan project : list) {
                Map<String,String> loan = new HashMap<>();
                loan.put("id",project.getProjectId().toString());
                loan.put("platform_name",plateform_name);
                loan.put("url",h5BorrowDetailUrl+project.getProjectId());
                loan.put("title",project.getTitle());
                loan.put("username",project.getBorrowUserId());
                loan.put("userid",project.getBorrowUserId());
                loan.put("status","1");
                loan.put("c_type",this.getCtyppFromProject(project).toString());
                loan.put("amount",project.getContractAmount().toString());
                loan.put("rate",project.getBorrowRate().toString());
                loan.put("period",project.getDeadline().toString());
                loan.put("p_type",DeadlineUnitEnum.BY_MONTH.getDeadlineUnit().equals(project.getDeadlineUnit())? "1":"0");
                loan.put("pay_way",this.getPayWayStr(project));
                loan.put("process","1.0");
                loan.put("prepayment_time",DateUtils.format(project.getOverTime(),DateUtils.SHOW_DATETIME_FORMAT));
                loan.put("accrual_end_time",loan.get("prepayment_time"));
                loan.put("end_time",DateUtils.format(project.getFullSuccessTime(),DateUtils.SHOW_DATETIME_FORMAT));
                loan.put("prepayment_type","0");
                loan.put("prepayment_amount",project.getRefundedCorpus().add(project.getRefundedInterest()).toString());
                loan.put("prepayment_accrual",project.getRefundedInterest().toString());
                loans.add(loan);
            }
        }
        responseDTO.setPage_count(countNum % dto.getPageSize() == 0 ?countNum/dto.getPageSize() : countNum/dto.getPageSize()+1);
        responseDTO.setPage_index(dto.getPageIndex());
        responseDTO.setResult_code(1);
        responseDTO.setResult_msg("成功");
        responseDTO.setLoans(loans);
        return responseDTO;
    }

}
